/**
 * StringEnumConverter
 *
 * @author Chris Pratt
 *
 * 12/15/2011
 */
package com.anodyzed.onyx.type;

public class StringEnumConverter implements Converter {

  /**
   * Convert Strings (or CharSequence's) to/from Enum's
   *
   * @param from Either a CharSequence or an Enum 
   * @param to The type to convert to 
   * @return Either an Enum or a String
   */
  @Override
  @SuppressWarnings({"unchecked","rawtypes"})
  public <T> T convert (Object from,Class<T> to) {
    if(from instanceof CharSequence) {
      try {
        return to.cast(Enum.valueOf((Class<? extends Enum>)to,from.toString()));
      } catch(IllegalArgumentException x) {
        throw new ConversionException("Unable to convert ''{0}'' ({0.class.name}) to a {1.name}",from,to,x);
      }
    } else if(from instanceof Enum) {
      return to.cast(((Enum<?>)from).name());
    }
    throw new ConversionException("{0.class.name} is neither a String (CharSequence) nor an Enum",from);
  } //convert

} //*StringEnumConverter
